<template>
  <div>
    <div class="basebar" ref="progressBar" @click="progressClick">
            <span class="progressbar for_point" ref="progress">
              <span id="now_point" ref="progressBtn"
                    @touchstart.prevent="progressTouchStart"
                    @touchmove.prevent="progressTouchMove"
                    @touchend="progressTouchEnd"
              ></span>
            </span>
    </div>
  </div>
</template>
<script>
  const progressBtnWidth = 20;
  import {prefixStyle} from 'common/js/dom'

  const transform = prefixStyle('transform')

  export default {
    props: {
      percent: {
        type: Number,
        default: 0
      }
    },
    created() {
      this.touch = {}
    },
    methods: {
      progressTouchStart(e) {
        this.touch.initiated = true
        this.touch.startX = e.touches[0].pageX
        this.touch.left = this.$refs.progress.clientWidth
      },
      progressTouchMove(e) {
        if (!this.touch.initiated) {
          return
        }
        const deltaX = e.touches[0].pageX - this.touch.startX
        const offsetWidth = Math.min(this.$refs.progressBar.clientWidth - progressBtnWidth, Math.max(0, this.touch.left + deltaX))
        this._offset(offsetWidth)
      },
      progressTouchEnd() {
        this.touch.initiated = false
        this._triggerPercent()
      },
      progressClick(e) {
        const rect = this.$refs.progressBar.getBoundingClientRect()
        const offsetWidth = e.pageX - rect.left
        this._offset(offsetWidth)
        // 这里当我们点击 progressBtn 的时候，e.offsetX 获取不对
        // this._offset(e.offsetX)
        this._triggerPercent()
      },
      _triggerPercent() {
        const barWidth = this.$refs.progressBar.clientWidth - progressBtnWidth
        const percent = this.$refs.progress.clientWidth / barWidth
        this.$emit('percentChange', percent)
      },
      _offset(offsetWidth) {
        this.$refs.progress.style.width = `${offsetWidth}px`
        // this.$refs.progressBtn.style[transform] = `translate3d(${offsetWidth}px,0,0)`
      }
    },
    watch: {
      percent(newPercent ) {
        if (newPercent >= 0 && !this.touch.initiated) {
          const barWidth = this.$refs.progressBar.clientWidth - progressBtnWidth/2
          const offsetWidth = newPercent * barWidth
          this._offset(offsetWidth)
        }
      }
    }
  }
</script>

<style>
  .progressbar {
    width: 100%;
  }

  .basebar {
    height: 4px;
    border-radius: 2px;
    background-color: #cecece;
    position: relative;
  }

  .progressbar {
    height: 4px;
    border-radius: 2px;
    background-color: #059692;
    position: absolute;
    /*width: 233px;*/
    display: inline-block;
    left: 0;
    top: 0;
  }

  /*.for_point {*/
    /*position: relative;*/
  /*}*/

  #now_point {
    width: 20px;
    height: 20px;
    border-radius: 50px;
    background-color: #059692;
    position: absolute;
    right: -20px;
    top: -8px;
    z-index: 2;
  }
</style>
